//
//  TopupVC.m
//  代理端
//
//  Created by sliver on 15/12/12.
//  Copyright (c) 2015年 sliver. All rights reserved.
//

#import "TopupVC.h"
#import "Unit.h"
#import "WXDataService.h"
#import "UPPayPlugin.h"
#import "UPPayPluginDelegate.h"
@interface TopupVC ()<UITextFieldDelegate,UPPayPluginDelegate,BackViewDeleget>
{
    UITextField *telTextField;
    NSInteger flag; //支付方式
 }
@end

@implementation TopupVC

- (void)viewDidLoad {
    [super viewDidLoad];
    flag = 1;
    [self loadNav];
    [self loadView1];
    // Do any additional setup after loading the view.
}
-(void)loadView1{
    //第一个输入框view
    UIView *view1 = [[UIView alloc]initWithFrame:CGRectMake(0, 60,ScreenW, 60)];
    view1.backgroundColor = [UIColor whiteColor];
    view1.layer.masksToBounds = YES;
    view1.layer.cornerRadius = 5;
    [self.view addSubview:view1];
    
    UILabel *lable =[[UILabel alloc]init];
    lable.frame = CGRectMake(20*KScr, 0, 180*KScr, 60);
    lable.textColor = [UIColor blackColor];
    lable.text =@"请输入充值金额";
    [view1 addSubview:lable];
    //输入TextField
    telTextField = [[UITextField alloc]initWithFrame:CGRectMake(200*KScr, 0, 120*KScr, 60)];
    telTextField.delegate = self;
    telTextField.font = [UIFont systemFontOfSize:18.0];
    telTextField.textAlignment = NSTextAlignmentRight;
    [telTextField becomeFirstResponder];
    telTextField.keyboardType = UIKeyboardTypeNumberPad;
    telTextField.returnKeyType = UIReturnKeyDone;
    [view1 addSubview:telTextField];
    //元
    UILabel *yuanLabel = [[UILabel alloc] initWithFrame:CGRectMake(320*KScr, 0, 20*KScr, 60)];
    yuanLabel.text = @"元";
    [view1 addSubview:yuanLabel];
    //选择充值方式
    UILabel *zhifufangshiLab = [[UILabel alloc]initWithFrame:CGRectMake(0, 125, ScreenW, 30)];
    zhifufangshiLab.text = @"   请选择充值方式:";
    zhifufangshiLab.backgroundColor = [UIColor whiteColor];
    zhifufangshiLab.font = [UIFont systemFontOfSize:15];
    [self.view addSubview:zhifufangshiLab];
    UIView *backview = [[UIView alloc]initWithFrame:CGRectMake(0, 156, ScreenW, WITH_FOR_45 *3-WITH_FOR_5)];
    backview.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:backview];
    NSArray *nameAry = @[@"银联充值",@"支付宝充值",@"微信充值"];
    NSArray *imgAry = @[@"union_pay-512",@"zhifubao",@"weixin"];
    for(int i =0;i<3;i++){
        UIImageView *imgview = [[UIImageView alloc]initWithFrame:CGRectMake(WITH_FOR_20, WITH_FOR_5 +WITH_FOR_45*i, WITH_FOR_30, WITH_FOR_30)];
        imgview.image = [UIImage imageNamed:imgAry[i]];
        imgview.backgroundColor = DRINK_LIGHTGRAY_COLOR;
        [backview addSubview:imgview];
        UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(WITH_FOR_60, WITH_FOR_10+WITH_FOR_45*i, WITH_FOR_100, WITH_FOR_20)];
        lab.text =nameAry[i];
        lab.font = [UIFont systemFontOfSize:17];
        lab.textColor = [UIColor blackColor];
        [backview addSubview:lab];
        
        UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(ScreenW - 30, WITH_FOR_20+WITH_FOR_45*i, 12, 12)];
        btn.layer.masksToBounds = YES;
        btn.layer.cornerRadius = 6;
        if(i == 0){
            btn.backgroundColor = DRINK_RED_COLOR;
        }else{
            btn.backgroundColor = [UIColor grayColor];
        }
        btn.tag = i+1;
        [backview addSubview:btn];
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(10, WITH_FOR_40+WITH_FOR_45*i, ScreenW-10, 1)];
        view.backgroundColor = DRINK_LIGHTGRAY_COLOR;
        [backview addSubview:view];
        
        UIButton *btnn = [[UIButton alloc]initWithFrame:CGRectMake(0, WITH_FOR_40*i, ScreenW, WITH_FOR_45)];
        btnn.backgroundColor = [UIColor clearColor];
        btnn.tag = i+10;
        [btnn addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
        [backview addSubview:btnn];
    }
    //确认按钮
    UIButton *landBtn = [[UIButton alloc]initWithFrame:CGRectMake(60, ScreenH - 100, ScreenW - 120, 40)];
    landBtn.backgroundColor = DRINK_RED_COLOR;
    landBtn.layer.masksToBounds = YES;
    landBtn.layer.cornerRadius = 5;
    [landBtn setTitle:@"确定" forState:UIControlStateNormal];
    landBtn.titleLabel.font = [UIFont boldSystemFontOfSize:15];
    [landBtn addTarget:self action:@selector(clickLand:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:landBtn];
}
#pragma mark - 充值
-(void)clickLand:(UIButton *)senfer{
     switch (flag) {
        case 1:{
              [self payByUPPayPlugin];
            return;
        }
         case 2:{
                 NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
                 [params setObject:USER_ACCOUNT forKey:@"agency_id_"];
                 [params setObject:telTextField.text forKey:@"total_fee"];
                 [params setObject:@(flag) forKey:@"type"];
                 [WXDataService requestWithURL:@"mobile/agency/rechargeBalance.jhtml" params:params httpMethod:@"POST" block:^(id result, NSString *success, NSString *msg) {
                     NSLog(@"%@",result);
                     [BackView addToview:self.view WithDeleget:self WithMessage:@"充值成功" WithBtnCount:1];
//                         UIAlertView *deleAlertView=[[UIAlertView alloc]initWithTitle:nil message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
//                         [deleAlertView show];
                         return;
                 }failblock:^(AFHTTPRequestOperation *operation, NSError *error) {
                     
                 }];

            break;
         }
         default:
            break;
    }
}
#pragma mark - 点击红点
-(void)clickBtn:(UIButton *)sender{
    for(int i=0;i<4;i++){
        UIButton *btn = (UIButton *)[self.view viewWithTag:i+1];
        btn.backgroundColor = [UIColor grayColor];
    }
    UIButton *btn = (UIButton *)[self.view viewWithTag:sender.tag - 9];
    btn.backgroundColor = DRINK_RED_COLOR;
    flag = btn.tag;
}
-(void)payByUPPayPlugin
{
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObject:@"2" forKey:@"keytype"];
    [params setObject:USER_ACCOUNT forKey:@"keyid"];
    [params setObject:[NSString stringWithFormat:@"%@00",telTextField.text] forKey:@"total_fee"];
    [WXDataService requestWithURL:@"sys_plugins/onlinepay/unionpay/getTn.jhtml" params:params httpMethod:@"POST" block:^(id result, NSString *success, NSString *msg) {
        NSLog(@"银联接口 = %@ - %@ - %@", success, msg, result);
        if ([success boolValue] == 1) {
            NSString *tn = [NSString stringWithFormat:@"%@", [result objectForKey:@"tn"]];
            [UPPayPlugin startPay:tn mode:@"00" viewController:self delegate:self];
        }
    }failblock:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}

-(void)UPPayPluginResult:(NSString*)result
{
    NSLog(@"银联支付结果 = %@", result);
    if ([result isEqualToString:@"success"]) {
        NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
        [params setObject:USER_ACCOUNT forKey:@"agency_id_"];
        [params setObject:telTextField.text forKey:@"total_fee"];
        [params setObject:@(flag) forKey:@"type"];
        [WXDataService requestWithURL:@"mobile/agency/rechargeBalance.jhtml" params:params httpMethod:@"POST" block:^(id result, NSString *success, NSString *msg) {
            UIAlertView *deleAlertView=[[UIAlertView alloc]initWithTitle:nil message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [deleAlertView show];
            return;
        }failblock:^(AFHTTPRequestOperation *operation, NSError *error) {
            
        }];

        
    }else if ([result isEqualToString:@"false"]){
        UIAlertView *deleAlertView=[[UIAlertView alloc]initWithTitle:nil message:@"支付失败" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [deleAlertView show];
        return;
    }else if ([result isEqualToString:@"cancel"]){
        UIAlertView *deleAlertView=[[UIAlertView alloc]initWithTitle:nil message:@"已取消支付" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [deleAlertView show];
        
        return;
    }
}
#pragma mark - nav
-(void)loadNav{
    self.view.backgroundColor = DRINK_LIGHTGRAY_COLOR;
    UIView *redview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenW, 20)];
    redview.backgroundColor = DRINK_RED_COLOR;
    [self.view addSubview:redview];
    UILabel *redLab = [[UILabel alloc]initWithFrame:CGRectMake(0, 20, ScreenW, 40)];
    redLab.backgroundColor = DRINK_RED_COLOR;
    redLab.text = @"充值";
    redLab.textColor = [UIColor whiteColor];
    redLab.textAlignment =  NSTextAlignmentCenter;
    redLab.font = [UIFont boldSystemFontOfSize:19];
    [self.view addSubview:redLab];
    UIButton *backBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 20,44, 40)];
    backBtn.adjustsImageWhenHighlighted = NO;
    [backBtn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(clickBack) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backBtn];
}
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    [telTextField resignFirstResponder];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
     [telTextField resignFirstResponder];
     return YES;
}
-(void)clickBack{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)makeSureButtenClic:(UIButton *)btn withMessage:(NSString *)message
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:USER_ACCOUNT forKey:@"agency_id_"];
    
[WXDataService requestWithURL:@"mobile/agency/getAgencyInfo.jhtml" params:dic httpMethod:@"POST" block:^(id result, NSString *success, NSString *msg) {
//    self.block();
    NSLog(@"%@",result);
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    [userDefaultes setObject:result[@"agencyPO"] forKey:@"USER_DIC"];
    [userDefaultes synchronize];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"changeValue" object:nil];
    
} failblock:^(AFHTTPRequestOperation *operation, NSError *error) {
    
}];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
